from agent.comment_agent import comment_with_agent
from models.chat_schemas import ChatRequest,ChatHistoryResponse
from models.json_response import JsonData
from core.exceptions import ApiException
from typing import Dict,Any
from fastapi import APIRouter, UploadFile, File, Form
from service.chat_service import ChatService 
from fastapi import Depends
from core.auth import get_currnt_user
from fastapi.responses import StreamingResponse, FileResponse
from agent.chat_agent import generate_stream_response
from service.file_service import FileService
from tools.ppt_tool import PPTGenerator
import json
import os
import tempfile

from pydantic import BaseModel

# 添加课程建议请求模型
class CourseSuggestionRequest(BaseModel):
    course_name: str = ""
    course_code: str = ""
    schedule: str = ""
    location: str = ""
    description: str = ""

router = APIRouter(
    prefix="/api/teach",
    tags=["教学助手"]
)

@router.get("/test")
async def test_endpoint():
    """测试接口"""
    return {"message": "课程建议接口测试成功"}

@router.post("/chat")
async def chat_stream(request: ChatRequest,
                  chat_service: ChatService = Depends(ChatService),
                    course_id: str = None,
                  account_id: str = None):
    # 简化版chat接口，不需要认证
    if not request.message:
        return JsonData.error("消息内容不能为空")
    
    # 转换文件信息为字典列表
    files = None
    if request.files:
        files = [file.dict() for file in request.files]
    
    # 使用默认参数
    default_account_id = account_id or "default_user"
    default_course_id = course_id or "default_course"
    
    return StreamingResponse(
        generate_stream_response(chat_service, default_account_id, request.message, default_course_id, files),
        media_type="text/event-stream"
    )

@router.post("/course-suggestion")
async def get_course_suggestion(
    request: CourseSuggestionRequest,
    chat_service: ChatService = Depends(ChatService)
):
    """
    获取课程建议接口
    """
    try:
        # 构建课程信息
        course_info = f"""
课程名称: {request.course_name}
课程代码: {request.course_code}
上课时间: {request.schedule}
上课地点: {request.location}
课程描述: {request.description}
        """.strip()
        
        # 构建AI提示词
        prompt = f"""你是一个专业的教学顾问，请根据以下课程信息提供专业的建议：

{course_info}

请从以下几个方面提供建议：
1. 课程名称是否合适（简洁性、准确性、吸引力）
2. 课程代码是否符合规范
3. 上课时间安排是否合理
4. 上课地点是否合适
5. 课程描述是否完整清晰
6. 整体课程设计的改进建议

请用中文回答，建议要具体实用，语言要专业但易懂。如果某些信息缺失，请指出并提供建议。
        """
        
        # 调用AI服务
        from core.llm import get_default_llm
        llm = get_default_llm()
        response = await llm.ainvoke(prompt)
        
        return JsonData.success(response.content)
        
    except Exception as e:
        import logging
        logger = logging.getLogger(__name__)
        logger.error(f"课程建议生成失败: {e}")
        return JsonData.error(f"生成课程建议失败: {str(e)}")

@router.post("/upload")
def upload_file(file: UploadFile = File(...),
                file_service: FileService = Depends(FileService),
               course_id: str = None,
                file_id: str = None):
    try:
        print(f"接收到文件上传请求: filename={file.filename}, content_type={file.content_type}, size={file.size}")
        
        # 简化处理，只保存文件不进行embedding
        import os
        upload_dir = "./file"
        os.makedirs(upload_dir, exist_ok=True)
        
        file_location = os.path.join(upload_dir, file.filename)
        contents = file.file.read()
        
        with open(file_location, "wb") as f:
            f.write(contents)
            
        print(f"文件保存成功: {file_location}")
        return JsonData.success(f"文件 {file.filename} 上传成功")
    except Exception as e:
        print(f"文件上传失败: {e}")
        return JsonData.error(f"上传失败: {str(e)}")

@router.post("/comment")
def comment(comments:str):
    """评论接口"""
    try:
        result = comment_with_agent(comments)
        return JsonData.success(result)
    except Exception as e:
        return JsonData.error(f"评论失败: {str(e)}")

@router.post("/generate-ppt")
async def generate_ppt(
    ppt_data: str = Form(...),
    filename: str = Form(...)
):
    """
    生成PPT文件接口
    """
    try:
        # 验证输入参数
        if not ppt_data or ppt_data.strip() == "":
            return JsonData.error("PPT数据不能为空")
        
        if not filename or filename.strip() == "":
            return JsonData.error("文件名不能为空")
        
        # 解析PPT数据
        try:
            ppt_content = json.loads(ppt_data)
        except json.JSONDecodeError as e:
            return JsonData.error(f"PPT数据格式错误: {str(e)}")
        
        # 验证必要的数据
        if not ppt_content.get('title'):
            return JsonData.error("PPT标题不能为空")
        
        if not ppt_content.get('slides') or len(ppt_content.get('slides', [])) == 0:
            return JsonData.error("PPT内容不能为空")
        
        # 创建PPT生成器
        ppt_generator = PPTGenerator()
        
        # 构建PPT内容
        content = f"""
课程标题：{ppt_content.get('courseInfo', {}).get('title', '')}

课程内容：{ppt_content.get('courseInfo', {}).get('content', '')}

知识点：
{chr(10).join([f"- {kp.get('name', '')}: {kp.get('content', '')}" for kp in ppt_content.get('courseInfo', {}).get('knowledgePoints', [])])}

AI建议：
{chr(10).join(ppt_content.get('courseInfo', {}).get('aiSuggestions', []))}
        """
        
        # 获取幻灯片数量
        slides_count = len(ppt_content.get('slides', []))
        if slides_count == 0:
            slides_count = 4  # 默认4页
        
        # 确保幻灯片数量在合理范围内
        slides_count = max(1, min(slides_count, 20))  # 1-20页之间
        
        # 生成PPT文件
        ppt_path = ppt_generator.generate(content, pages=slides_count)
        
        # 检查文件是否存在
        if not os.path.exists(ppt_path):
            raise Exception("PPT文件生成失败")
        
        # 检查文件大小
        file_size = os.path.getsize(ppt_path)
        if file_size < 1000:  # 小于1KB可能是错误文件
            raise Exception("生成的PPT文件异常")
        
        # 返回文件
        return FileResponse(
            path=ppt_path,
            filename=filename,
            media_type='application/vnd.openxmlformats-officedocument.presentationml.presentation'
        )
        
    except Exception as e:
        import logging
        logger = logging.getLogger(__name__)
        logger.error(f"PPT生成失败: {str(e)}")
        return JsonData.error(f"PPT生成失败: {str(e)}")